package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Configuration configuration;//freemarker 配置对象


    /**
     * 分页查询
     *
     * @param queryPageBean
     * @return
     */
    public PageResult findPage(QueryPageBean queryPageBean) {
        //设置分页参数
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);

        Page<Setmeal> page = setmealMapper.selectByCondition(queryString);

        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 新增套餐
     *
     * @param setmeal
     * @param checkgroupIds
     */

    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealMapper.add(setmeal);
        //获取 新增的套餐的id
        Integer setmealId = setmeal.getId();
        String imgName = setmeal.getImg();

        if (imgName != null && !imgName.isEmpty()) {
            // 将图片加入 Redis 的集合中
            redisTemplate.opsForSet().add("all_uploaded_pics", imgName);
            redisTemplate.opsForSet().add("valid_setmeal_pics", imgName);
        }
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                // 循环插入关联表
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);

                setmealMapper.setSetmealAndCheckGroup(map);
            }
        }
        //  生成静态页面
        generateMobileStaticHtml();

    }

    /**
     * 根据套餐id查询套餐数据
     *
     * @param id
     */
    public Setmeal findById(Integer id) {
        return setmealMapper.findById(id);
    }

    /**
     * 编辑套餐
     *
     * @param setmeal
     * @param checkGroupIds
     */

    public void edit(Setmeal setmeal, Integer[] checkGroupIds) {
        // 1. 更新套餐基本信息
        setmealMapper.edit(setmeal);

        // 2. 获取原始套餐数据
        Setmeal originalSetmeal = setmealMapper.findById(setmeal.getId());
        String oldImgName = originalSetmeal.getImg(); // 注意字段名是否是 img 还是 pic
        String newImgName = setmeal.getImg();

        // 3. 如果上传了新图片，需要更新 Redis 集合
        if (newImgName != null && !newImgName.isEmpty()) {
            // 1. 移除旧图片（如果存在）
            if (oldImgName != null && !oldImgName.isEmpty()) {
                redisTemplate.opsForSet().remove("all_uploaded_pics", oldImgName);
                redisTemplate.opsForSet().remove("valid_setmeal_pics", oldImgName);
            }

            // 2. 添加新图片到 all_uploaded_pics 和 valid_setmeal_pics
            redisTemplate.opsForSet().add("all_uploaded_pics", newImgName);
            redisTemplate.opsForSet().add("valid_setmeal_pics", newImgName);
        }


        // 4. 如果有关联的检查组，则先删除旧关联，再添加新关联
        if (checkGroupIds != null && checkGroupIds.length > 0) {
            Integer setmealId = setmeal.getId();

            // 4.1 删除旧关联
            setmealMapper.deleteSetmealAndCheckGroupBySetmealId(setmealId);

            // 4.2 插入新的关联记录
            for (Integer checkGroupId : checkGroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkGroupId);
                setmealMapper.setSetmealAndCheckGroup(map);
            }
        }
    }

    //  查询套餐预约占比
    public List<Map<String, Object>> findSetmealCount() {
        return setmealMapper.findSetmealCount();
    }





    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml() {
        //查询数据
        List<Setmeal> list = setmealMapper.findAll();
        //生成套餐静态列表页面
        generateMobileSetmealListHtml(list);
        //生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);

    }
    //生成套餐静态列表页面
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap<>();
        //为模板提供数据
        map.put("setmealList", list);
        generateHtml("mobile_setmeal.ftl", "setmeal.html", map);

    }
    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {

        for (Setmeal setmeal : list) {
            //为模板提供数据
            Map<String, Object> map = new HashMap<>();
            map.put("setmeal",setmealMapper.findById4Detail(setmeal.getId()) );
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }

    }


    //生成静态页面
    public void generateHtml(String teplateName, String htmlPageName, Map map) {

        //  创建 freemarker 配置对象
        //Configuration configuration = new Configuration(Configuration.getVersion());
       /* //设置模板目录
        configuration.setDirectoryForTemplateLoading(new File("bxg-health-backend/src/main/resources/templates/mobile_setmeal.ftl"));
        //设置字符集
        configuration.setDefaultEncoding("utf-8");*/
        //加载模板
        configuration.setDefaultEncoding("utf-8");
        Writer out = null;
        try {
            Template template = configuration.getTemplate(teplateName);
            out = new FileWriter(new File("D:\\ftl\\" + htmlPageName));
            //输出文件
            template.process(map, out);
            out.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

}
